import {Injectable, NestInterceptor, ExecutionContext, CallHandler, Logger} from '@nestjs/common';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {WxLoggerService} from '../services/logger.service';
import {connect, model} from 'mongoose';
import {WxLoggerSchema} from '../model/schema/logger.schema';

connect('mongodb://localhost/wxlog').then((r) => Logger.log('mongo', 'mongo connect'));
export const WxLogger = model('Logger', WxLoggerSchema, 'logger');

@Injectable()
export class LoggingInterceptor implements NestInterceptor {

    // tslint:disable-next-line:no-any
    async handleAsync(context: ExecutionContext, data: any, old: number) {

        const httpHost = context.switchToHttp();
        const response = httpHost.getResponse();
        const request = httpHost.getRequest();

        const now = Date.now();
        const current = now - old;

        const value = {
            url: request.url,
            delayTime: current + 'ms',
            currentTime: (new Date(now)).toLocaleString(),
            value: JSON.stringify(data),
        };
        Logger.log(data, request.url);
        const log = new WxLogger(value);
        await log.save();
    }

    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

        const now = Date.now();
        return next
            .handle()
            .pipe(
                tap((data) => this.handleAsync(context, data, now)),
            );
    }
}
